package coco.core
{
	import coco.component.group.GroupPanel;
	import coco.util.App;
	import coco.util.WindowUtil;
	
	import flash.desktop.Updater;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	import mx.core.FlexGlobals;
	import mx.managers.PopUpManager;
	
	public class MyUpdater
	{
		
		private var nowVersion:String;
		private var newVersion:String;
		private var newApp:String;
		private var autoTip:Boolean = false;
		
		private static var instance:MyUpdater;
		public static function getInstance():MyUpdater
		{
			if(!instance)
				instance = new MyUpdater();
			
			return instance;
		}
		
		public function MyUpdater()
		{
			var xml:XML = FlexGlobals.topLevelApplication.nativeApplication.applicationDescriptor;
			var nss:Namespace = xml.namespace();
			nowVersion = xml.nss::versionNumber;
		}
		/**
		 *异步下载并解释更新描述符文件 
		 */		
		public function checkForUpdate(tip:Boolean = false):void
		{
			autoTip = tip;
			var updateUrl:String = App.UPDATER_URL;
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, loadErrorHandler);
			urlLoader.load(new URLRequest(updateUrl));
		}
		
		private function loadCompleteHandler(e:Event):void
		{
			try
			{
				var updateXML:XML = new XML(e.currentTarget.data);
				var ns:Namespace = updateXML.namespace();
				newVersion = updateXML.ns::version;
				newApp = updateXML.ns::url;
				var des:XML = new XML(updateXML.ns::description);
				
				if(newVersion != nowVersion)
				{
					var text:String = '<p>更新版本: ' + newVersion + '</p>' +
						'<p>当前版本: ' + nowVersion + '</p>' +
						des.toString();
					var panel:GroupPanel = new GroupPanel();
					panel.content = text;
					panel.addEventListener('update', updateHandler);
					PopUpManager.addPopUp(panel, FlexGlobals.topLevelApplication as DisplayObject, true);
					PopUpManager.centerPopUp(panel);
				}
				else
				{
					if(autoTip)
						WindowUtil.toolTip('当前已经是最新版本');
				}
			}
			catch(e:Error)
			{
				trace(e.toString());
			}
		}
		
		private var tempFile:File;
		private function updateHandler(e:Event):void
		{
			tempFile = File.applicationDirectory.resolvePath('version/coco.air');
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, airResult);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, airError);
			urlLoader.addEventListener(ProgressEvent.PROGRESS, airProgress);
			urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
			urlLoader.load(new URLRequest(newApp));
		}
		
		private function airResult(e:Event):void
		{
			var fs:FileStream = new FileStream();
			fs.open(new File(tempFile.nativePath), FileMode.WRITE);
			fs.writeBytes(e.currentTarget.data);
			fs.close();
			
			startUpdate(tempFile, newVersion);
		}
		
		private function airError(e:Event):void
		{
			WindowUtil.toolTip('更新错误');
		}
		
		
		private function airProgress(e:ProgressEvent):void
		{
			WindowUtil.progress(int(e.bytesLoaded / e.bytesTotal * 100));
		}
		
		
		private function loadErrorHandler(e:IOErrorEvent):void
		{
		}
		
		
		private function startUpdate(file:File, version:String):void
		{
			WindowUtil.progress(100);
			var updater:Updater = new Updater();
			updater.update(file, version);
		}
	}
}